package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 按照状态查询用户认证列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1参数检查
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();//重新检查参数

            //2条件查询
        Page page = new Page(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        if(dto.getStatus() != null){
            query.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage result = page(page, query);

        //3返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }


    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Autowired
    ApUserMapper apUserMapper;


    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询apUserRealName
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null || userRealname.getUserId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2.获取apUser id
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null || apUser.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_STATUS_ERROR);
        }

        //3.修改状态2 9
        userRealname.setStatus(status);
        userRealname.setCreatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);

        //4.如果审核通过
        if (status.intValue() == AdminConstants.PASS_AUTH.intValue()){
            //4.1 远程创建自媒体账号
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null || wmUser.getId() == null){
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }
            //4.2 远程创建作者账号
            boolean flag = createApAuthor(wmUser);
            if(!flag){
                CustException.cust(AppHttpCodeEnum.AUTHOR_ADD_ERROR);
            }
            //5 更新APUser 数据中 flag = 1
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }
//        int i = 1 / 0;
        //6 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    ArticleFeign articleFeign;
    private Boolean createApAuthor(WmUser wmUser) {
        boolean flag = false;
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2); // 自媒体人类型
            apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
            apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
            ResponseResult result = articleFeign.save(apAuthor);
            // code=0
            if (result.getCode() == 0) {
                flag = true;
            }
        }

        return flag;
    }

    @Autowired
    WemediaFeign wemediaFeign;
    //远程创建自媒体账号
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //2 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setApUserId(apUser.getId());
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
            //成功后返回新增的主键
            wmUser =  wemediaFeign.save(wmUser);

            if (wmUser.getId() != null) {
                return wmUser;
            }
        }

        return null;
    }
}
